/**
 * Editor actions related functionality for ArenaNext
 * Handles integration with Monaco editor including registering editor actions
 */

// 设置要忽略的错误代码
export const errorsToIgnore = [80001];

/**
 * Registers editor actions for AI assistance in the Monaco editor
 * @param {Object} monacoController - The Monaco controller instance
 * @param {Function} chatRunner - Function to handle chat-related editor actions
 */
export function registerEditorActions(monacoController, chatRunner) {
  // Get Monaco instance
  const monaco = monacoController.monacoController.monaco;
  const editor = monaco.editor;

  // Register AI-related editor actions
  editor.addEditorAction({
    id: "ChatJPTMistakesSelectedCode",
    label: "纠正代码错误",
    contextMenuGroupId: "chatJPT",
    contextMenuOrder: 1,
    run: () => chatRunner(1),
  });

  editor.addEditorAction({
    id: "ChatJPTFunctionSelectedCode",
    label: "长函数拆分",
    contextMenuGroupId: "chatJPT",
    contextMenuOrder: 1.5,
    run: () => chatRunner(13),
  });

  editor.addEditorAction({
    id: "ChatJPTExplainSelectedCode",
    label: "优化重构代码",
    contextMenuGroupId: "chatJPT",
    contextMenuOrder: 2,
    run: () => chatRunner(2),
  });

  editor.addEditorAction({
    id: "ChatJPTInterpretationSelectedCode",
    label: "详细解释代码",
    contextMenuGroupId: "chatJPT",
    contextMenuOrder: 3,
    run: () => chatRunner(3),
  });

  editor.addEditorAction({
    id: "ChatJPTExegesisSelectedCode",
    label: "注释生成",
    contextMenuGroupId: "chatJPT",
    contextMenuOrder: 6,
    run: () => chatRunner(6),
  });

  // Register actions for all code analysis
  editor.addEditorAction({
    id: "ChatJPTAllCode",
    label: "所有脚本质量评估",
    contextMenuGroupId: "chatJPTAllCode",
    contextMenuOrder: 1,
    run: () => chatRunner(9999, true),
  });

  editor.addEditorAction({
    id: "ChatJPTAllCodeStructure",
    label: "所有脚本代码结构分析",
    contextMenuGroupId: "chatJPTAllCode",
    contextMenuOrder: 4,
    run: () => chatRunner(14, true),
  });
}

/**
 * Sets up auto-formatting when the user presses Enter
 * @param {Object} monacoController - The Monaco controller instance
 */
export function setupAutoFormatOnEnter(monacoController) {
  try {
    const monaco = monacoController.monacoController.monaco;
    const editorInstance = monacoController.monacoController.monacoEditor;

    // 获取格式化文档操作
    const formatAction = editorInstance._actions.get(
      "editor.action.formatDocument"
    );

    if (!formatAction) {
      console.warn("未找到格式化文档操作");
      return;
    }

    // 添加键盘事件监听器以处理Enter键
    editorInstance.onKeyDown((e) => {
      if (e.keyCode === 3) {
        // Enter键的keyCode
        setTimeout(() => {
          formatAction._run();
        }, 0);
      }
    });
  } catch (error) {
    console.error("设置Enter键自动格式化失败:", error);
  }
}

/**
 * Registers code quick fix provider for error handling
 * @param {Object} monacoController - The Monaco controller instance
 * @param {Function} customChatRunner - Function to handle custom chat requests
 */
export function registerQuickFixProvider(monacoController, customChatRunner) {
  const monaco = monacoController.monacoController.monaco;

  // 注册快速修复提供器
  monaco.languages.registerCodeActionProvider("javascript", {
    provideCodeActions: function (model, range, context, token) {
      const errorMarkers = context.markers;

      if (!errorMarkers || errorMarkers.length === 0) {
        return {
          actions: [],
          dispose: () => {},
        };
      }

      const actions = [];

      errorMarkers.forEach((marker) => {
        if (
          marker.severity === monaco.MarkerSeverity.Error ||
          marker.severity === monaco.MarkerSeverity.Warning
        ) {
          const action = {
            title: `Chat吉PT修复`,
            kind: "quickfix",
            edit: {
              edits: [],
            },
            isPreferred: true,
            diagnostics: [marker],
            command: {
              id: "editor.action.customQuickFix",
              title: "吉PT修复",
              arguments: [model, marker],
            },
          };

          actions.push(action);
        }
      });

      return {
        actions: actions,
        dispose: () => {},
      };
    },
  });

  // 注册命令处理快速修复
  monaco.editor.registerCommand(
    "editor.action.customQuickFix",
    function (_, model, marker) {
      // 在编辑器中选择错误行
      const editor = monaco.editor.getEditors()[0];
      editor.setSelection({
        startLineNumber: marker.startLineNumber,
        startColumn: 1,
        endLineNumber: marker.endLineNumber,
        endColumn: model.getLineMaxColumn(marker.endLineNumber),
      });

      // 聚焦编辑器使选择可见
      editor.focus();

      const startLine = Math.max(1, marker.startLineNumber - 5);
      const endLine = Math.min(model.getLineCount(), marker.endLineNumber + 5);

      let codeWithContext = "";
      for (let i = startLine; i <= endLine; i++) {
        codeWithContext += model.getLineContent(i) + "\n";
      }

      const errorDescription = marker.message;

      // 使用自定义聊天运行器处理修复
      customChatRunner(
        90,
        `该代码报错："${errorDescription}"，请帮我解释一下错误原因，并给出修复建议和完整修复后的JavaScript代码，如有类型错误，须使用jsdoc加上类型注释。`
      );
    }
  );
}
